﻿using System;
using System.Collections.Generic;
using System.Text;
using BBMS.DLL.Base;
using System.Collections;
using System.Windows.Forms;
using System.Drawing;

namespace BBMS.BLL.Implementation
{
    public class AsyncCore
    {
        private ListView _listObj;
        ToolStripComboBox _txCbxPage;
        private Label _statusLbl;
        private ListObjectDelegate _invokeMe;
        protected FilterParams fParams = new FilterParams();
        private int curPage;
        private int totalPage;

        private delegate ArrayList ListObjectDelegate(out int curPage, out int totalPage, FilterParams fParams);

        public AsyncCore(ObjectBase objectbase, ListView listObj, ToolStripComboBox txCbxPage, Label statusLbl)
        {
            this._listObj = listObj;
            this._statusLbl = statusLbl;
            this._txCbxPage = txCbxPage;
            this._invokeMe = new ListObjectDelegate(objectbase.GetObjectByPage);
        }

        private void Execute()
        {
            //Update UI here
            MethodInvoker updateUIState = delegate
            {
                _statusLbl.BackColor = Color.Red;
            };
            if (_statusLbl.InvokeRequired)
                _statusLbl.Invoke(updateUIState);
            else
                updateUIState();
            _invokeMe.BeginInvoke(out curPage, out totalPage, fParams, this.CallBack, null);
        }

        private void CallBack(IAsyncResult ar)
        {
            try
            {
                ArrayList objList = _invokeMe.EndInvoke(out curPage, out totalPage, ar);

                //Update UI here
                MethodInvoker updateUIState = delegate
                {
                    _txCbxPage.Items.Clear();
                    for (int i = 0; i < fParams.TotalPage; i++)
                        _txCbxPage.Items.Add(i + 1);

                    if (_txCbxPage.Items.Count > 0) _txCbxPage.SelectedIndex = fParams.CurrentPage - 1;

                    if (objList == null || objList.Count == 0)
                        MessageBox.Show("Không có bản ghi nào trong cơ sở dữ liệu.");
                    else
                    {
                        foreach (ObjectBase obj in objList)
                            AddNewObjectToList(obj);
                    }

                    if (ar.IsCompleted)
                        _statusLbl.BackColor = Color.Green;
                };
                if (_statusLbl.InvokeRequired)
                    _statusLbl.Invoke(updateUIState);
                else
                    updateUIState();
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        protected virtual void AddNewObjectToList(ObjectBase obj) { }

    }
}
